home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10167 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  86 lines

  1. Path: news.magicnet.net!usenet
  2. From: catello@magicnet.net (Michael Catello)
  3. Newsgroups: comp.lang.c++
  4. Subject: object creation from an abstract base class
  5. Date: Wed, 06 Mar 1996 04:10:23 GMT
  6. Organization: MagicNet, Inc.
  7. Message-ID: <4hj32e$e2t@comet.magicnet.net>
  8. NNTP-Posting-Host: pm2-13.magicnet.net
  9. X-Newsreader: Forte Free Agent 1.0.82
  10.  
  11. Hello OOPsters,
  12.  
  13. I was just looking for validation/other suggestions for a method I
  14. recently used in a program. I have defined an abstract base class
  15. (i.e. contains pure virtual functions), all access to the derived
  16. classes of this base are thru a pointer to the base class. To create
  17. the actual objects of the derived classes I used the following scheme:
  18.  
  19.  
  20. enum FooType {BAR, BAS};
  21.  
  22. // base class
  23. class CFoo
  24.     {
  25.     CFoo();
  26.     ~CFoo();
  27.     
  28.     static CFoo* CreateFoo(FooType type);
  29.  
  30.     // other methods/data including pure virtual fns whose behaviour will
  31. be defined in the derived classes
  32.     };
  33.  
  34. class CBar: public CFoo
  35.     {
  36.     // 
  37.     };
  38.  
  39. class CBas: public CFoo
  40.     {
  41.     // 
  42.     };
  43.  
  44. CFoo* CFoo::CreateFoo(FooType type)
  45.     {
  46.     CFoo* pfoo = NULL;
  47.  
  48.     switch (type)
  49.         {
  50.         case BAR:
  51.             pfoo = new CBar;
  52.             break;
  53.         case BAS:
  54.             pfoo = new CBas;
  55.             break;
  56.         }
  57.  
  58.     return pfoo;
  59.     }
  60.  
  61. main()
  62.     {
  63.     CFoo* interface = CFoo::CreateFoo(BAR);
  64.     }
  65.  
  66. Obviously it is the CreateFoo() function that I am wondering about. In
  67. the actual implementation I had multiple static "Create" functions for
  68. the base class that would allow me to create a new object: one based
  69. on an enumerated token (shown above), another an existing object, as
  70. well as one based on the format of a datafile. My application never
  71. references any of the derived classes directly, except in their
  72. creation and definition.
  73.  
  74. Is there another/better/more appropriate way to handle this type of
  75. object creation? Thanks for your assistance,
  76.  
  77. Regards,
  78. -Michael.
  79.  
  80. /*
  81.  * catello@magicnet.net
  82.  * http://www.magicnet.net/~catello
  83.  * CompuServe: 70401,3661
  84.  */
  85.  
  86.